﻿using Nop.Core;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web.Hosting;

namespace Spotshub.Plugin.Payments.GlobalPayments.Services
{
    public class Helper
    {
        public static string GetSampleFileContent(string resourceName)
        {
            string fullResourceName = string.Format("Spotshub.Plugin.Payments.GlobalPayments.Samples.{0}", resourceName);
            var assem = System.Reflection.Assembly.GetAssembly(typeof(Helper));
            using (var stream = assem.GetManifestResourceStream(fullResourceName))
            {
                using (var reader = new StreamReader(stream))
                    return reader.ReadToEnd();
            }
        }

        public static string BuildUrlWithQuery(string url, NameValueCollection queryStrs)
        {
            return url + queryStrs.ToQueryString();
        }

        public static string GetDirectService(string url, bool log = false)
        {
            string res = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = "GET";

                FileLog("GetDirectService", url, log);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream dataStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(dataStream);
                    res = reader.ReadToEnd();
                    reader.Close();
                    dataStream.Close();
                    
                    FileLog("GetDirectService", res, log);
                }
            }
            catch (Exception exc)
            {
                throw new NopException("Failed to get direct service. Url: {0}, Exception: {1}", url, exc);
            }

            return res;
        }

        public static string PostDirectService(string url, bool log = false)
        {
            string res = null;
            try
            {
                FileLog("PostDirectService", url, log);

                using (WebClient wc = new WebClient())
                {
                    res = wc.UploadString(url, "POST", "");
                    
                    FileLog("PostDirectService", res, log);
                }
            }
            catch (Exception exc)
            {
                throw new NopException("Failed to post direct service. Url: {0} Exception: {1}", url, exc);
            }

            return res;
        }

        public static string GetHeaderString(NameValueCollection headers, string method)
        {
            var sb = new System.Text.StringBuilder();

            sb.AppendLine(DateTime.UtcNow.ToLongTimeString());
            sb.AppendFormat("Method: {0} ", method);
            sb.AppendLine("Headers:");

            foreach (var header in headers.AllKeys)
            {
                sb.AppendFormat("{0} : {1}", header, headers[header]);
            }
            return sb.ToString();
        }

        public static void FileLog(string name, string message, bool enabled = true)
        {
            if (enabled && !String.IsNullOrEmpty(message))
            {
                string filename = Path.Combine(GetAppDataDir(), String.Format("GP_{0}.log", name));
                using (var file = new System.IO.StreamWriter(filename, true))
                {
                    file.WriteLine(DateTime.Now.ToShortTimeString());
                    file.WriteLine(message);
                }
            }
        }

        private static string _appDataDir = null;
        public static string GetAppDataDir()
        {
            if (_appDataDir == null)
            {
                if (HostingEnvironment.IsHosted)
                {
                    //hosted
                    _appDataDir = HostingEnvironment.MapPath("~/App_Data");
                }
                else
                {
                    //not hosted. For example, run in unit tests
                    string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    _appDataDir = Path.Combine(baseDirectory, "App_Data");
                }
            }
            return _appDataDir;
        }
        //public static T DeserializeXml<T>(string xml) where T : class
        //{
        //    using (var sr = new StringReader(xml))
        //    {
        //        return DeserializeXml<T>(sr);
        //    }
        //}

        //public static T DeserializeXml<T>(TextReader xml) where T : class
        //{
        //    XmlSerializer s = new XmlSerializer(typeof(T));

        //    using (var r = XmlReader.Create(xml))
        //    {
        //        T res = default(T);
        //        if (s.CanDeserialize(r))
        //        {
        //            res = s.Deserialize(r) as T;
        //        }
        //        return res;
        //    }
        //}
    }
}
